package evolution;

import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.io.StringWriter;

import evolution.Directory;
import evolution.File;
import evolution.ResourceException;


public class StubFile implements File
{
	private String name;
	private String content = "";
	private Directory parent;
	private long lastModified;
	private final TimeKeeper timeKeeper;

	public StubFile(String name, TimeKeeper timeKeeper)
	{
		this.name = name;
		this.timeKeeper = timeKeeper;
		this.lastModified = timeKeeper.currentTime();
	}

	public void setContent(String content)
	{
		this.content = content;
	}

	public String getName()
	{
		return name;
	}

	public Reader getReader() throws ResourceException
	{
		return new StringReader(content);
	}

	public Writer getWriter() throws ResourceException
	{
		return new StringWriter()
		{
			@Override
            public void close()
			{
				content = toString();
				lastModified= timeKeeper.currentTime();
			}
		};
	}

	public void setParent(Directory parent)
	{
		this.parent = parent;
	}

	public String getPath()
	{
		if (parent != null)
		{
			String parentPath = parent.getPath();
			if (parentPath.equals("/"))
			{
				return "/" + getName();
			}
			else
			{
				return parentPath + "/" + getName();
			}
		}
		else
		{
			return getName();
		}
	}

	public long getLastModifiedTime()
	{
		return lastModified;
	}

	@Override
	public String toString()
	{
		return getPath();
	}

}
